const fs = require('fs');
const esbuild = require('esbuild');

async function build() {
  await esbuild.build({
    entryPoints: ['bin/server'],
    bundle: true,
    platform: 'node',
    target: ['node14'],
    outfile: 'dist/server.bundle.js',
    external: [
      'book', 
      'koa', 
      'tldjs', 
      'debug', 
      'http', 
      'human-readable-ids', 
      'koa-router',
      'localenv',
      'optimist'
    ],
    format: 'cjs',
  });

  // 读取生成的文件
  let content = fs.readFileSync('dist/server.bundle.js', 'utf8');
  
  // 移除所有的 shebang
  content = content.replace(/^#!.*\n/gm, '');
  
  // 添加正确的 shebang
  content = `#!/usr/bin/env node -r esm\n${content}`;
  
  // 写回文件
  fs.writeFileSync('dist/server.bundle.js', content);
  
  // 添加执行权限
  fs.chmodSync('dist/server.bundle.js', '755');
}

build().catch(() => process.exit(1));
